//
//  ViewController.m
//  TxyxSDKDemo
//
//  Created by Karate on 2021/11/23.
//

#import "ViewController.h"
#import <TxyxSDK/TxyxSDK.h>
#import "TXDetailView.h"

#define kScreenWidth  [[UIScreen mainScreen] bounds].size.width
#define kScreenHeight [[UIScreen mainScreen] bounds].size.height
#define kHPX(px)  [self heightWithPX:px]
#define kWPX(px)  [self weightWithPX:px]
#define kSize(px) [self sizeWithPX:px]

@interface ViewController () <ChangePriceDelegate> {
    
}

@property (nonatomic, strong) UIView          *btnView;
@property (nonatomic, strong) UIButton        *loginBtn;
@property (nonatomic, copy) NSString        *loginInfo;
@property (nonatomic, assign) UIInterfaceOrientation currentOrientation;
@property (nonatomic, assign) BOOL            isLogin;

@property (nonatomic, strong) UILabel         *tipsLab;

@property (nonatomic, copy) NSString        *curPayPrice;


@end

@implementation ViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.curPayPrice = @"1";
    
    self.currentOrientation = [[UIApplication sharedApplication] statusBarOrientation];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarOrientationChange:) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
    
    self.loginInfo = @"";
    self.isLogin   = NO;
    [self initBaseView];
    
    NSLog(@"当前版本：%@",[[TXUtilsFactory sharedInstance] versionStr]);
    [self gainCurrentGameStatus];
    
    __block ViewController *blockSelf = self;
    [[TxyxSDK sharedInstance] setExitLogin:^(NSDictionary *resultDic) {
        NSLog(@"[exitLogin] resultDic = %@", resultDic);
        blockSelf.loginInfo = @"";
        blockSelf.isLogin   = NO;
        blockSelf.loginBtn.titleLabel.font = [UIFont fontWithName:@"PingFang-SC-Medium" size:kSize(52)];
        [blockSelf.loginBtn setTitle:@"登录" forState:UIControlStateNormal];
        [blockSelf.loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            // 调用登录接口事件
            [self showLoginView];
        });
    }];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    // [UIApplication sharedApplication].keyWindow不为空的时候才去调用登录,登录界面才会显示
    // 登录功能
    if (!_isLogin) {
        [self showLoginView];
    }
}

/** 设置初始界面 */
- (void)initBaseView {
    UIImageView *backImgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    [backImgView setImage:[UIImage imageNamed:@"bg_image.png"]];
    [self.view addSubview:backImgView];
    
    self.btnView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    [self.view addSubview:self.btnView];
    
    // 按钮
    NSArray *btnArr = @[@"登录",@"支付",@"参数",@"上传角色",@"注销"];
    CGFloat btnW = kWPX(350);
    CGFloat btnH = kHPX(330);
    CGFloat btnX = (self.view.frame.size.width - btnW * 2 - kWPX(20)) / 2;
    CGFloat btnY = (self.view.frame.size.height - btnH * 2 - kHPX(120) - kHPX(20) *2) / 2;

    for (int i = 0; i < btnArr.count; i ++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        if (i < 2) {
            btn.frame = CGRectMake(btnX + (btnW + kWPX(20)) * i, btnY, btnW, btnH);
        }else if (i < 4) {
            btn.frame = CGRectMake(btnX + (btnW + kWPX(20)) * (i - 2), btnY + kHPX(20) + btnH, btnW, btnH);
        }else {
            btn.frame = CGRectMake(btnX, btnY + (btnH + kHPX(20)) * 2, kWPX(720), btnH / 2);
        }
        btn.tag = i;
        
        btn.titleLabel.font = [UIFont fontWithName:@"PingFang-SC-Medium" size:kSize(40)];
        [btn setTitle:btnArr[i] forState:UIControlStateNormal];
        btn.backgroundColor = [UIColor colorWithRed:76 / 255.0 green:76 / 255.0 blue:76 / 255.0 alpha:0.7];
        btn.layer.cornerRadius  = kWPX(30);
        btn.layer.masksToBounds = YES;
        [btn addTarget:self action:@selector(clickBaseBtn:) forControlEvents:UIControlEventTouchUpInside];
        if (i == 0) {
            self.loginBtn = btn;
            if (self.loginInfo.length) {
                [self.loginBtn setTitle:self.loginInfo forState:UIControlStateNormal];
                self.loginBtn.titleLabel.font = [UIFont fontWithName:@"PingFang-SC-Medium" size:kSize(44)];
                [self.loginBtn setTitleColor:[UIColor colorWithRed:25 / 255.0 green:177 / 255.0 blue:234 / 255.0 alpha:1.0] forState:UIControlStateNormal];
            }
        }
        [self.btnView addSubview:btn];
    }
    
    UILabel *versionLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, self.btnView.frame.size.height - 30, 100, 30)];
    versionLabel.backgroundColor = [UIColor clearColor];
    versionLabel.font = [UIFont systemFontOfSize:14.0];
    versionLabel.textColor = [UIColor whiteColor];
    versionLabel.text = [NSString stringWithFormat:@"SDK版本:%@", [[TXUtilsFactory sharedInstance] versionStr]];
    [self.btnView addSubview:versionLabel];
}

/** 显示登录界面 */
- (void)showLoginView {
    /**
     * addLoginView: 调用登录的控制器view,使用self.view
     * gameInfo: 应用信息
     * completion: 登录结果回调
     */
    __weak __typeof(self) weakself= self;
    [[TxyxSDK sharedInstance] addLoginView:^(NSDictionary *resultDic) {
        
        //根据登录返回信息，进行相关操作
        NSLog(@"[showLogin] resultDic = %@", resultDic);
        NSString *loginRes = [NSString stringWithFormat:@"%@", [resultDic objectForKey:@"loginresult"]];
        if([@"1" isEqualToString:loginRes]){
            NSString *userId = [NSString stringWithFormat:@"%@", [resultDic objectForKey:@"userId"]];
            NSString *nickname = resultDic[@"nickname"];// 用户昵称
            NSLog(@"登录成功,userId=%@", userId);
            self.isLogin   = YES;
            self.loginInfo = userId;
            [self.loginBtn setTitle:nickname forState:UIControlStateNormal];
            self.loginBtn.titleLabel.font = [UIFont fontWithName:@"PingFang-SC-Medium" size:kSize(44)];
            [self.loginBtn setTitleColor:[UIColor colorWithRed:25 / 255.0 green:177 / 255.0 blue:234 / 255.0 alpha:1.0] forState:UIControlStateNormal];
            
        }else if ([@"0" isEqualToString:loginRes]){
            [weakself showTip:@"登录失败"];
        }else{
            NSLog(@"返回主页");
        }
    }];
}

/** 按钮 */
- (void)clickBaseBtn:(UIButton *)sender {
    
    //    UIButton *loginBtn = [self.view viewWithTag:0];
    if (sender.tag == 0) {
        // 登录功能
//        NSLog(@"登录功能");
//        if (!self.isLogin) {
//            [self showLoginView];
//        }
        
    } else if (sender.tag == 1) {
        // 充值
        NSLog(@"充值 pay ");
        TXOrderInfo *orderInfo = [[TXOrderInfo alloc] init];
        orderInfo.goodsName = @"金币";
        orderInfo.goodsPrice = self.curPayPrice; //单位为分
        orderInfo.goodsDesc = @"10金币";
        orderInfo.extendInfo = [self getNowTimeTimestamp];//游戏订单号(不能重复)，此字段会透传到游戏服务器，可拼接订单信息和其它信息等
        orderInfo.productId = @"coin";//虚拟商品ID，内购为APP Store中的ID
        orderInfo.gameVersion = @"1.0.0";//游戏版本号
        __weak __typeof(self) weakself= self;
        [[TxyxSDK sharedInstance] exchange:orderInfo completionBlock:^(NSDictionary *resultDic) {
            NSLog(@"[pay] resultDic = %@", resultDic);
            NSString *payRes = [NSString stringWithFormat:@"%@", [resultDic objectForKey:@"result"]];
            if([@"1" isEqualToString:payRes]){
                [weakself showTip:@"支付成功"];
            }
            else if([@"0" isEqualToString:payRes]){
                [weakself showTip:@"支付失败"];
            }
        }];
    } else if (sender.tag == 2) {
        // 参数
        TXDetailView *detailView = [[TXDetailView alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, [[UIScreen mainScreen] bounds].size.height)];
        [detailView setDelegate:self];
        [self.view addSubview:detailView];
    } else if (sender.tag == 3) {
        // 上报角色
        NSLog(@"上报角色");
        
        // 创建角色信息
        TXRoleInfo *roleInfo = [[TXRoleInfo alloc]init];
        roleInfo.serverId = @"1";            //区服ID
        roleInfo.serverName = @"浪漫樱花";    //区服名称
        roleInfo.roleId = @"1000";            //角色ID
        roleInfo.roleName = @"西门吹雪";        //角色名称
        roleInfo.roleLevel = @"12";            //角色等级
        
        __weak __typeof(self) weakself= self;
        [[TxyxSDK sharedInstance] uploadRoleInfo:roleInfo completionBlock:^(NSDictionary *resultDict) {
            
            NSString *payRes = [NSString stringWithFormat:@"%@", [resultDict objectForKey:@"status"]];
            if([@"200" isEqualToString:payRes]){
                NSLog(@"角色上报成功");
                [weakself showMsg:@"角色上报成功"];
            }else{
                [weakself showTip:resultDict[@"return_msg"]];
            }
        }];
    } else if (sender.tag == 4) {
        // 注销按钮。会执行 setExitLogin:^(NSDictionary *resultDic) {} 回调方法
        NSLog(@" 注销按钮 ");
        if (!self.isLogin) {
            // 未登录
            [self showMsg:@"请先登录"];
        } else {
            // 已登录
            [[TxyxSDK sharedInstance] clickLoginOut];
        }
    }
}

// 防沉迷功能
- (void)gainCurrentGameStatus{
    [[TXUtilsFactory sharedInstance] getUserType:^(NSDictionary *resultDic){
        /**  返回字段说明
         * currentGameType: 当前用户游戏状态  OnlineFirstTime、OnlineSecondTime、SleepFullTime、HoursContentOff
         * force_close: 是否强制关闭游戏  0：是 1：否
         */
        NSLog(@"getUserType：%@",resultDic);
        if([resultDic[@"currentGameType"] isEqualToString:@"OnlineFirstTime"]){
            NSLog(@"继续玩游戏就是疲劳游戏，经验减半");
        }else if ([resultDic[@"currentGameType"] isEqualToString:@"OnlineSecondTime"]){
            NSLog(@"继续玩游戏就是处于休息中，没有经验");
        }else if ([resultDic[@"currentGameType"] isEqualToString:@"HoursContentOff"]){
            NSLog(@"未实名认证循环提示开启了");
        }else{
            NSLog(@"状态恢复");
        }
    }];
}

- (void)showTip:(NSString *)tipstr{
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                    message:tipstr delegate:nil cancelButtonTitle:nil
                                          otherButtonTitles:@"确定",nil];
    [alert show];
}

- (void)showMsg:(NSString *)msgStr {
    
    CGFloat tipsLabW = kWPX(460);
    _tipsLab = [[UILabel alloc]initWithFrame:CGRectMake((self.view.frame.size.width - tipsLabW) / 2, self.view.frame.size.height - kHPX(208) - kHPX(110), tipsLabW, kHPX(110))];
    _tipsLab.text = msgStr;
    _tipsLab.textAlignment = NSTextAlignmentCenter;
    _tipsLab.font = [UIFont fontWithName:@"PingFang-SC-Medium" size:kWPX(38)];
    _tipsLab.textColor = [UIColor whiteColor];
    _tipsLab.layer.cornerRadius  = kHPX(55);
    _tipsLab.layer.masksToBounds = YES;
    _tipsLab.backgroundColor = [UIColor colorWithRed:98.0 / 255.0 green:212.0 / 255.0 blue:255.0 / 255.0 alpha:0.7];
    [self.view addSubview:_tipsLab];
    
    [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(hiddenTipsLab) userInfo:nil repeats:NO];
}

- (void)hiddenTipsLab {
    [_tipsLab removeFromSuperview];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

// 获取当前时间戳有两种方法(以秒为单位)
- (NSString *)getNowTimeTimestamp {
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    //设置时区,这个对于时间的处理有时很重要
    
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [formatter setTimeZone:timeZone];
    
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];
    return timeSp;
}


/** 设置PX与iOS尺寸高度的转换 */
- (CGFloat)heightWithPX:(int)px {
    CGSize size = [[UIScreen mainScreen] bounds].size;
    CGFloat height = px * size.height / (736.0 * 3);
    if(size.width > size.height) {
        // 横屏
        height = px * size.height / (414.0 * 3);
    }
    return height;
}

/** 设置PX与iOS尺寸宽度的转换 */
- (CGFloat)weightWithPX:(int)px {
    CGSize size = [[UIScreen mainScreen] bounds].size;
    CGFloat weight = px * size.width / (414.0 * 3);
    if(size.width > size.height) {
        // 横屏
        weight = px * size.width / (736.0 * 3);
    }
    return weight;
}

/** 字体大小与UI给的px对应关系 */
- (CGFloat)sizeWithPX:(int)px {
    CGSize size = [[UIScreen mainScreen] bounds].size;
    CGFloat fontSize = px * size.width / (414.0 * 2);
    if(size.width > size.height) {
        // 横屏
        fontSize = px * size.width / (736.0 * 2);
    }
    //    CGFloat size = px *  [UIScreen mainScreen].bounds.size.width / (414.0*3);
    return fontSize;
}

#pragma mark - ChangePriceDelegate

- (void)returnPopsPrice:(NSString *)priceStr {
    self.curPayPrice = priceStr;
}

#pragma mark - NSNotification

- (void)statusBarOrientationChange:(NSNotification *)notification{
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
    switch (orientation){
        case UIInterfaceOrientationPortrait:
        case UIInterfaceOrientationPortraitUpsideDown:
        case UIInterfaceOrientationLandscapeLeft:
        case UIInterfaceOrientationLandscapeRight:
            if (self.currentOrientation == orientation){
                break;
            }
            self.currentOrientation = orientation;
            [self.btnView removeFromSuperview];
            [self initBaseView];
            break;
        default:
            break;
    }
}


@end
